package com.ktjy.market.controller;

import com.ktjy.market.mapper.BackendUserMapper;
import com.ktjy.market.pojo.BackendUser;
import com.ktjy.market.service.BackendUserService;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import utils.Constants;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

@Controller
@RequestMapping("/manager")
public class BackendUserController {

    private Logger logger=Logger.getLogger(BackendUserController.class);

    @Resource
    private BackendUserService backendUserService;


    @RequestMapping("/toBackendLogin")
    public String doBackendLogin(){
        return "/backendlogin";
    }

    @RequestMapping("/toMain")
    public String toMain(){
        return "/backend/main";
    }

    @RequestMapping("/login")
    public String login(@RequestParam("userCode")String user,
                        @RequestParam("userPassword")String password,
                        HttpSession session){
        int i = backendUserService.getUserCount(user);
        if (i > 0) {
            //调用service方法，进行用户匹配
            BackendUser backendUser = backendUserService.login(user, password);
            if (null != backendUser) {
                //将登录用户放入session
                session.setAttribute(Constants.USER_SESSION, backendUser);
                //登录成功，重定向到/user/toMain接口
                return "redirect:/manager/toMain";
            } else {
                session.setAttribute("error","密码输入错误!");
            }
        } else {
            //用户不存在，登录失败
            session.setAttribute("error","用户名不存在!");
        }
        return "redirect:/manager/toBackendLogin";
    }
}
